package main

import (
	"fmt"
	"math/rand"
	"sync"
	"time"
)

/*
	工作池：控制并发数量，避免资源耗尽
*/

// 工作任务
type Job struct {
	ID   int
	Data string
}

// 处理结果
type Result struct {
	Job    Job
	Output string
	Error  error
}

func worker(id int, jobs <-chan Job, results chan<- Result, wg *sync.WaitGroup) {
	defer wg.Done()

	for job := range jobs {
		fmt.Printf("Worker %d processing job %d: %s\n", id, job.ID, job.Data)

		// 模拟处理时间
		time.Sleep(time.Duration(rand.Intn(1000)) * time.Millisecond)

		// 模拟处理结果
		result := Result{
			Job:    job,
			Output: fmt.Sprintf("Processed: %s", job.Data),
		}

		results <- result
		fmt.Printf("Worker %d completed job %d\n", id, job.ID)
	}
}

func main() {
	// 创建job和result channel
	jobs := make(chan Job, 100)
	results := make(chan Result, 100)

	// 创建工作任务
	go func() {
		for i := 1; i <= 20; i++ {
			jobs <- Job{
				ID:   i,
				Data: fmt.Sprintf("task_data_%d", i),
			}
		}
		close(jobs)
	}()

	// 启动worker池
	var wg sync.WaitGroup
	for i := 1; i <= 5; i++ { // 5个worker
		wg.Add(1)
		go worker(i, jobs, results, &wg)
	}

	// 收集结果
	go func() {
		wg.Wait()
		close(results)
	}()

	// 输出结果
	fmt.Println("=== 处理结果 ===")
	for result := range results {
		fmt.Printf("Result: Job %d -> %s\n", result.Job.ID, result.Output)
	}

	fmt.Println("所有任务完成!")
}
